<?php


namespace App\Http\Controllers\Backend;


use App\Services\Other\Models\WechatPlatform;
use App\Services\Company\Models\Company;
use App\Zesow\WechatOpenPlatform;
use EasyWeChat\Kernel\Exceptions\RuntimeException;
use EasyWeChat\OpenPlatform\Server\Guard;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Str;


class WechatOpenController extends BaseController
{


    public function callback(Request $request)
    {

        try {
            $openPlatform = WechatOpenPlatform::getInstance();
            // 第三方平台接入处理
            $server = $openPlatform->server;
            // 处理授权成功事件
            $server->push(function ($event) use ($openPlatform) {
                //获取（刷新）授权公众号或小程序的接口调用凭据（令牌）
                $res = $openPlatform->handleAuthorize($event['AuthorizationCode']);
                $appid2 = $res['authorization_info']['authorizer_appid'];
                $refresh_token = $res['authorization_info']['authorizer_refresh_token'];

                //获取授权方的帐号基本信息
                $data = $openPlatform->getAuthorizer($appid2);
                $info2 = $data['authorizer_info'];
                $info1 = $data['authorization_info'];

                //绑定开放平台账户
                $app = $openPlatform->miniProgram($appid2, $refresh_token);
                $account = $app->account;

                $data = $account->getBinding();
                if (!$data['errcode'] == 0) {
                    $account->create();
                    $account->bindTo($openPlatform->config->get('app_id'));
                }

                $mini = WechatPlatform::query()->where('app_id', $appid2)->first();
                if (!$mini) {
                    $mini = new  WechatPlatform();
                }
                $idArray = array_map(function ($item) {
                    return $item["funcscope_category"]["id"];
                }, $info1['func_info']);
                $funcs = implode("|", $idArray);

                $mini->app_id = $info1['authorizer_appid'];
                $mini->refresh_token = $refresh_token;
                $mini->func_info = $funcs;
                $mini->name = $info2['nick_name'];
                $mini->com_main_body = $info2['principal_name'];
                $mini->headimg = $info2['qrcode_url'];
                $mini->type = 0;
                $mini->status = 1;
                $mini->original = $info2['user_name'];
                $mini->level = $this->getLevel($info2);
                $mini->head_img = $info2['head_img'];
                $mini->token = Str::random(32);
                $mini->encodingaeskey = Str::random(43);
                $mini->save();

            }, Guard::EVENT_AUTHORIZED);


            // 处理授权更新事件
            $server->push(function ($event) use ($openPlatform) {
                $res = $openPlatform->handleAuthorize($event['AuthorizationCode']);
                $appid2 = $res['authorization_info']['authorizer_appid'];
                $refresh_token = $res['authorization_info']['authorizer_refresh_token'];
                $mini = WechatPlatform::query()->where('app_id', $appid2)->first();
                if (!$mini) {
                    $mini = new  WechatPlatform();
                }
                $mini->app_id = $appid2;
                $data = $openPlatform->getAuthorizer($appid2);
                $info2 = $data['authorizer_info'];
                $info1 = $data['authorization_info'];
                $mini->refresh_token = $refresh_token;
                $mini->headimg = $info2['qrcode_url'];
                $mini->name = $info2['nick_name'];
                $mini->com_main_body = $info2['principal_name'];
                $mini->head_img = $info2['head_img'];
                $mini->type = 0;
                $mini->original = $info2['user_name'];
                $mini->level = $this->getLevel($info2);
                //更新权限集
                $idArray = array_map(function ($item) {
                    return $item["funcscope_category"]["id"];
                }, $info1['func_info']);
                $funcs = implode("|", $idArray);
                $mini->func_info = $funcs;
                $mini->head_img = $info2['head_img'];
                $mini->save();


            }, Guard::EVENT_UPDATE_AUTHORIZED);

            // 处理授权取消事件
            $server->push(function ($event) {
                $appid = $event['AuthorizerAppid'];
                $account = WechatPlatform::query()->where('app_id', $appid)->first();
                if (!is_null($account)) {
                    $account->delete();
                }
            }, Guard::EVENT_UNAUTHORIZED);


            return $server->serve();

        } catch (\Exception $e) {
            if (env('APP_DEBUG')) {
                echo $e->getMessage();
            } else {
                abort(404);
            }
        }


    }

    public function getLevel($info = array())
    {
        $level = 0;
        if (!empty($info['MiniProgramInfo'])) {
            $level = 5;
        } else if ($info['service_type_info']['id'] == 0 || $info['service_type_info']['id'] == 1) {
            //订阅号
            if ($info['verify_type_info']['id'] >= 0) {
                //已认证
                $level = 3;
            } else {
                $level = 1;
            }
        } else if ($info['service_type_info']['id'] == 2) {
            //服务号
            if ($info['verify_type_info']['id'] >= 0) {
                //已认证
                $level = 4;
            } else {
                $level = 2;
            }
        }
        return $level;

    }

    public function message(Request $request)
    {


        $openPlatform = WechatOpenPlatform::getInstance();
        $server = $openPlatform->server;

// 处理授权成功事件
        $server->push(function ($message) {
            // ...
        }, Guard::EVENT_AUTHORIZED);

// 处理授权更新事件
        $server->push(function ($message) {
            // ...
        }, Guard::EVENT_UPDATE_AUTHORIZED);

// 处理授权取消事件
        $server->push(function ($message) {
            // ...
        }, Guard::EVENT_UNAUTHORIZED);

    }


    /**
     * 添加授权链接
     * @return Application|Factory|View
     * @throws RuntimeException
     */
    public function getAuthUrl(Request $request)
    {

        $redirectUrl = $request->input('redirect_url', 'http://shop.zesow.com');
        $companyId = $this->loginCompanyId();
        $openPlatform = WechatOpenPlatform::getInstance();
        $url = $openPlatform->getPreAuthorizationUrl(route('company.wechat.bind.callback', ['company_id' => $companyId, 'redirect_url' => $redirectUrl]), ['auth_type' => 2]);
        return view('index.wechat_url', compact('url'));

    }

    /**
     * 绑定公司跟小程序
     * @param Request $request
     * @return Application|RedirectResponse|Redirector
     */
    public function bindApp(Request $request)
    {


        $redirectUrl = $request->input('redirect_url');
        $openPlatform = WechatOpenPlatform::getInstance();
        $authorizationCode = $request->input('auth_code');
        $res = $openPlatform->handleAuthorize($authorizationCode);
        $appid = $res['authorization_info']['authorizer_appid'];
        $redirectUrl =   url_append_query($redirectUrl,['app_id'=>$appid]);
        return redirect($redirectUrl);


    }

    public function syncCompany(Request $request)
    {
        $appId = $request->input('app_id');
        $companyId = $this->loginCompanyId();
        $mini = WechatPlatform::query()->where('app_id', $appId)->first();
        if (!$mini) {
           return  $this->error(__('数据暂未同步'));
        }
        Company::query()->where('id', $companyId)->update(['is_bind_mini' => 1]);
        $mini->update(['company_id' => $companyId]);
        return $this->successData(compact('mini'));


    }


}